// src/screens/LoginScreen.js
import React, { useState, useEffect } from 'react';
import { View, TextInput, Button, Text, Alert, TouchableOpacity, StyleSheet, Platform, ScrollView } from 'react-native';
import api from '../services/api';
import { useDispatch } from 'react-redux';
import { setUserInfo } from '../store/userSlice';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Geolocation from 'react-native-geolocation-service';
import { getLocationServiceForCoordinates, getLoginOptionsForCountry } from '../utils/locationService';
import WeChat from '../services/wechat';
import { GoogleSignin, statusCodes } from '@react-native-google-signin/google-signin';

const LoginScreen = ({ navigation }) => {
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [region, setRegion] = useState('Global'); // Default region
  const [availableLoginOptions, setAvailableLoginOptions] = useState([
    'phone', 
    'google', 
    'facebook',
    'wechat'
  ]);
  
  const dispatch = useDispatch();

  // Detect user's region on component mount
  useEffect(() => {
    detectUserRegion();
    configureGoogleSignIn();
  }, []);

  const configureGoogleSignIn = () => {
    GoogleSignin.configure({
      scopes: ['https://www.googleapis.com/auth/drive.readonly'], // what API you want to access on behalf of the user, default is email and profile
      webClientId: '731470904542-mmtse7lq4sv1lh23ibem3d1n9tohe55r.apps.googleusercontent.com', // client ID of type WEB for your server (needed to verify user ID and offline access)
      offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER
    });
  };

  const detectUserRegion = async () => {
    try {
      // First check if we have cached location data
      const cachedLocation = await AsyncStorage.getItem('userLocation');
      if (cachedLocation) {
        const locationData = JSON.parse(cachedLocation);
        updateLoginOptionsByCountry(locationData.country);
        return;
      }

      // Try to get current position
      Geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords;
          const locationService = getLocationServiceForCoordinates(latitude, longitude);
          
          // For now, we'll just use the location service to determine region
          // In a real app, you would reverse geocode to get the actual country
          if (locationService === 'AMap') {
            // User is likely in China
            updateLoginOptionsForCountry('China');
          } else {
            // User is likely outside China
            updateLoginOptionsForCountry('Global');
          }
        },
        (error) => {
          console.log('Location detection failed:', error);
          // Default to global options if location detection fails
          updateLoginOptionsForCountry('Global');
        },
        {
          enableHighAccuracy: true,
          timeout: 15000,
          maximumAge: 10000,
        }
      );
    } catch (error) {
      console.log('Error detecting user region:', error);
      // Default to global options if anything fails
      updateLoginOptionsForCountry('Global');
    }
  };

  const updateLoginOptionsByCountry = (country) => {
    setRegion(country);
    const options = getLoginOptionsForCountry(country);
    setAvailableLoginOptions(options);
  };

  const updateLoginOptionsForCountry = (country) => {
    setRegion(country);
    const options = getLoginOptionsForCountry(country);
    setAvailableLoginOptions(options);
  };

  const handleLogin = async () => {
    if (!phone || !password) {
      Alert.alert('错误', '请输入手机号和密码');
      return;
    }

    console.log(`开始登录，手机号: ${phone}`);
    setLoading(true);
    try {
      // 清理手机号，去除空格等不可见字符
      const cleanPhone = phone.trim();
      console.log(`清理后手机号: ${cleanPhone}`);
      const response = await api.login(cleanPhone, password);
      console.log('登录响应数据:', response);
      
      // 检查响应数据是否存在且包含access_token
      if (response && response.access_token) {
        const token = response.access_token;
        console.log('登录成功，设置token');
        // 设置API token
        await api.setToken(token);
        // 获取当前用户信息
        console.log('获取当前用户信息');
        const userResponse = await api.getCurrentUser();
        console.log('用户信息:', userResponse);
        
        // 检查是否为新用户（缺少昵称、性别或生日字段）
        const user = userResponse.data;
        const isNewUser = !user.nickname || !user.gender || !user.birthday;
        
        // 存储用户信息到Redux
        dispatch(setUserInfo({ token, user }));
        
        // 根据用户类型导航到不同页面
        if (isNewUser) {
          // 新用户需要完善资料
          navigation.navigate('CompleteProfile');
        } else {
          // 老用户直接进入主页
          navigation.replace('Main');
        }
      } else {
        console.log('服务器返回无效数据');
        Alert.alert('登录失败', '服务器返回无效数据');
      }
    } catch (error) {
      console.log('登录出错:', error);
      if (error.response) {
        console.log('后端返回错误:', error.response.data);
        Alert.alert('登录失败', JSON.stringify(error.response.data));
      } else if (error.request) {
        console.log('网络请求失败:', error.request);
        Alert.alert('登录失败', '网络请求失败，请检查网络连接和服务器状态');
      } else {
        console.log('未知错误:', error.message);
        Alert.alert('登录失败', error.message || '未知错误');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleGoogleLogin = async () => {
    try {
      await GoogleSignin.hasPlayServices();
      const userInfo = await GoogleSignin.signIn();
      console.log('Google登录成功:', userInfo);
      
      // 这里应该调用后端API完成登录流程
      Alert.alert('提示', 'Google登录功能正在开发中');
    } catch (error) {
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        // user cancelled the login flow
        Alert.alert('提示', '用户取消了登录');
      } else if (error.code === statusCodes.IN_PROGRESS) {
        // operation (e.g. sign in) is in progress already
        Alert.alert('提示', '登录正在进行中');
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        // play services not available or outdated
        Alert.alert('提示', 'Google Play服务不可用');
      } else {
        // some other error happened
        console.error('Google登录失败:', error);
        Alert.alert('登录失败', error.message || 'Google登录失败');
      }
    }
  };

  const handleSocialLogin = async (provider) => {
    switch(provider) {
      case 'google':
        handleGoogleLogin();
        break;
      case 'facebook':
        Alert.alert('提示', 'Facebook登录功能将在后续版本中实现');
        break;
      case 'wechat':
        try {
          // 注册微信应用
          await WeChat.registerApp('YOUR_WECHAT_APP_ID');
          
          // 检查是否安装了微信
          const isInstalled = await WeChat.isWXAppInstalled();
          if (!isInstalled) {
            Alert.alert('提示', '请先安装微信');
            return;
          }
          
          // 执行微信登录
          const result = await WeChat.login('YOUR_WECHAT_APP_ID');
          console.log('微信登录结果:', result);
          
          // 这里应该调用后端API完成登录流程
          Alert.alert('提示', '微信登录功能正在开发中');
        } catch (error) {
          console.error('微信登录失败:', error);
          Alert.alert('登录失败', error.message || '微信登录失败');
        }
        break;
      case 'apple':
        Alert.alert('提示', 'Apple登录功能将在后续版本中实现');
        break;
      case 'kakao':
        Alert.alert('提示', 'Kakao登录功能将在后续版本中实现');
        break;
      case 'vk':
        Alert.alert('提示', 'VK登录功能将在后续版本中实现');
        break;
      default:
        Alert.alert('提示', `${provider}登录功能将在后续版本中实现`);
    }
  };

  const renderSocialLoginButtons = () => {
    return (
      <View style={styles.socialLoginContainer}>
        {availableLoginOptions.map(option => {
          if (option === 'phone') return null;
          
          let title = '';
          let color = '';
          
          switch(option) {
            case 'google':
              title = '使用Google登录';
              color = '#4285F4';
              break;
            case 'facebook':
              title = '使用Facebook登录';
              color = '#4267B2';
              break;
            case 'wechat':
              title = '使用微信登录';
              color = '#07c160';
              break;
            case 'apple':
              title = '使用Apple登录';
              color = '#000000';
              break;
            case 'kakao':
              title = '使用Kakao登录';
              color = '#FEE500';
              break;
            case 'vk':
              title = '使用VK登录';
              color = '#45668E';
              break;
            default:
              title = `使用${option}登录`;
              color = '#2196F3';
          }
          
          return (
            <Button 
              key={option}
              title={title}
              onPress={() => handleSocialLogin(option)}
              color={color}
            />
          );
        })}
      </View>
    );
  };

  return (
    <ScrollView contentContainerStyle={styles.container}>
      <Text style={styles.title}>
        用户登录
      </Text>
      
      <Text style={styles.regionIndicator}>
        当前区域: {region}
      </Text>
      
      <TextInput
        placeholder="请输入手机号"
        value={phone}
        onChangeText={setPhone}
        keyboardType="phone-pad"
        style={styles.input}
      />
      
      <TextInput
        placeholder="请输入密码"
        secureTextEntry
        value={password}
        onChangeText={setPassword}
        style={styles.input}
      />
      
      <Button 
        title={loading ? "登录中..." : "登录"} 
        onPress={handleLogin} 
        disabled={loading}
      />

      {renderSocialLoginButtons()}
      
      <View style={styles.footer}>
        <Text>还没有账号？</Text>
        <TouchableOpacity onPress={() => navigation.navigate('Register')}>
          <Text style={styles.link}>立即注册</Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
    flexGrow: 1,
    justifyContent: 'center'
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 15
  },
  regionIndicator: {
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 15,
    color: '#666'
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    padding: 10,
    marginBottom: 15
  },
  socialLoginContainer: {
    marginVertical: 10,
  },
  footer: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 20
  },
  link: {
    color: 'blue',
    marginLeft: 5
  }
});

export default LoginScreen;